from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse, HttpResponse
import hashlib
import time
from App.models import Student
def hello(request):
    response = HttpResponse()
    # response.content = "德玛西亚one shui"
    # response.status_code = 404
    response.write("听说马桶堵了")
    response.flush()
    return response

def get_ticket(request):
    # if random.randrange(10) > 5:
    #     return HttpResponseRedirect('/app/hello/')
    #
    # return HttpResponse("恭喜您抢到十一回家的票")
    url = reverse('app:hello')
    print(url)

    # return HttpResponseRedirect(url)
    return redirect(url)

def get_info(request):
    data = {
        "status": 200,
        "msg": "ok",
    }
    return JsonResponse(data=data)

def set_cookie(request):
    response = HttpResponse("设置Cookie")
    response.set_cookie('username', 'Rock')
    return response

def get_cookie(request):
    username = request.COOKIES.get("username")
    return HttpResponse(username)

def login(request):
    return render(request, 'login.html')

def do_login(request):
    uname = request.POST.get('uname')
    response = HttpResponseRedirect(reverse('app:mine'))
    # response.set_cookie('uname', uname, max_age=60)
    response.set_signed_cookie('content', uname, "Rock")
    return response

def mine(request):
    # uname = request.COOKIES.get("content")
    try:
        uname = request.get_signed_cookie("content", salt="Rock")
        if uname:
            # return HttpResponse(uname)
            return render(request, 'mine.html', context={"uname": uname})
    except Exception as e:
        print("获取失败")
    return redirect(reverse('app:login'))

def logout(request):
    response = redirect(reverse("app:login"))
    response.delete_cookie("content")
    return response
# --------------------------------------------------------------

def hello2(request):
    return HttpResponse("Hello Two")


def login2(request):
    if request.method == "GET":
        return render(request, 'two_login.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        request.session["username"] = username
        return HttpResponse("登录成功")


def mine2(request):
    username = request.session.get("username")
    return render(request, 'two_mine.html', context=locals())


def logout2(request):
    response = redirect(reverse('app:mine2'))
    # del request.session['username']
    # response.delete_cookie('sessionid')
    # session cookie一起干掉
    request.session.flush()
    return response


def register(request):
    if request.method == "GET":
        return render(request, 'student_register.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        try:
            student = Student()
            student.name = username
            student.password = password
            student.save()
        except Exception as e:
            return redirect(reverse("app:register"))
        return HttpResponse("注册成功")


def student_login(request):
    if request.method == "GET":
        return render(request, 'student_login.html')
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        students = Student.objects.filter(name=username).filter(password=password)
        if students.exists():
            student = students.first()
            ip = request.META.get("REMOTE_ADDR")
            token = generate_token(ip, username)
            student.token = token
            student.save()
            # response = HttpResponse("用户登录成功")
            #
            # response.set_cookie("token", token)
            #
            # return response
            data = {
                "status": 200,
                "msg": "login success",
                "token": token
            }
            return JsonResponse(data=data)
        # return redirect(reverse("two:student_login"))
        data = {
            "status": 800,
            "msg": "verify fail"
        }
        return JsonResponse(data=data)


def generate_token(ip, username):
    tim = time.ctime()
    r = username
    return hashlib.new("md5", (ip + tim + r).encode("utf-8")).hexdigest()


def student_mine(request):
    # token = request.COOKIES.get("token")
    token = request.GET.get('token')
    try:
        student = Student.objects.get(token=token)
    except Exception as e:
        return redirect(reverse("app:student_login"))
    # return HttpResponse(student.s_name)
    data = {
        "msg": "ok",
        "status": 200,
        "data": {
            "username": student.name
        }
    }
    return JsonResponse(data=data)